package com.shortlink.common.util;

public class Base62Util {
    /**
     * Base62 字符集
     */
    private static final String BASE62_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    /**
     * Base62 编码
     */
    public static String encode(long value) {
        StringBuilder base62 = new StringBuilder();
        
        while (value > 0) {
            int remainder = (int) (value % 62);
            base62.append(BASE62_ALPHABET.charAt(remainder));
            value /= 62;
        }

        return base62.reverse().toString();
    }

    /**
     * Base62 解码
     */
    public static long decode(String base62Str) {
        long value = 0;
        for (int i = 0; i < base62Str.length(); i++) {
            char c = base62Str.charAt(i);
            int index = BASE62_ALPHABET.indexOf(c);
            value = value * 62 + index;  // 将每一位对应的值按 Base62 进制转换
        }
        return value;
    }
}
